package com.hi.hiparty.ui.fragment;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.hi.hiparty.R;
import com.hi.hiparty.entity.Party;
import com.hi.hiparty.entity.Post;
import com.hi.hiparty.location.BaiduMapService;
import com.hi.hiparty.ui.session.UserSession;
import com.hi.hiparty.ui.session.UserSessionManager;
import com.hi.hiparty.util.ApiHelper;
import com.hi.hiparty.util.Constants;
import com.hi.hiparty.util.Executor;
import com.hi.hiparty.util.FileUtils;
import com.hi.hiparty.util.HttpUtil;
import com.hi.hiparty.util.ImageDownloader;
import com.hi.hiparty.util.ImageUtil;
import com.hi.hiparty.util.LocationUtil;
import com.hi.hiparty.util.PictureHandler;
import com.hi.hiparty.util.StringUtils;
import com.hi.hiparty.util.TimeUtils;
import com.hi.hiparty.util.UpLoaderPicUtil;

public class PartyDetailFragment extends SherlockFragment implements OnClickListener {

	public static final String TAG = PartyDetailFragment.class.getSimpleName();

	private static PictureHandler picHandler = PictureHandler.getInstance("partyDetail");
	
	private final SherlockFragment sf = this;
	
	public void init(){
		picHandler.addCommondForCode(
        		PictureHandler.REQUEST_PARTYDETAIL_CAMERA, new Executor() {
        			public void excute() {
        				Bitmap photo = this.getIntent().getParcelableExtra("image");
        			        if(photo != null ) {
        			        	try {
        			        		photo = ImageUtil.createBitmapBySizelimit(photo,800);
        			        		ImageUtil.saveJPGE_After(photo, Constants.USER_TEMP_PIC);
        			        		//处理list中上传图片USER_TEMP_PIC
        			        		final String upUrl = FileUtils.getUploadPicPath(session.getUserid(),FileUtils.getSuffix(Constants.USER_TEMP_PIC));		
        			        		new UpLoaderPicUtil.UploadTask().execute(
        			        				this.getActivity(),upUrl,Constants.USER_TEMP_PIC,new UpLoaderPicUtil.Callback(){
    											@Override
    											public void execute() {
    												Party p = mParty;
    												PostTask postTask = new PartyDetailFragment.PostTask();
    												postTask.execute("1",p.getPartyid(),session.getUserid(),upUrl);
    											}
        	    			        });
        			        	} catch (Exception e) {
        			        		e.printStackTrace();
        			        	}
        			}	
        		}});
	}
	private UserSession session = UserSessionManager.getUserSession(getActivity());;
	
	private Party mParty;

	private List<Post> mPosts;

	private ListView mListView = null;

	private View mPostTypeSelectPanel = null;

	private ImageButton mPostTypeSelectButton;

	private PostListAdapter mPostListAdapter = null;

	private static final int page_size = 30;

	private EditText mPostText;

	public void setParty(Party party) {
		mParty = party;
	}

	{
		init();
	}
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);

		if (savedInstanceState != null)
			setParty((Party) savedInstanceState.getSerializable("party"));
	}

	public void onSaveInstanceState(Bundle savedInstanceState) {
		super.onSaveInstanceState(savedInstanceState);
		savedInstanceState.putSerializable("party", mParty);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		View headerView = View.inflate(getActivity(), R.layout.party_detail_header, null);
		if (null != headerView && null != mParty) {
			TextView partyHolderNameView = (TextView) headerView.findViewById(R.id.text_party_holder_name);
			partyHolderNameView.setText(mParty.getUserid());

			TextView partyTimeView = (TextView) headerView.findViewById(R.id.party_start_time);
			partyTimeView.setText(TimeUtils.formatDateTimeShort(mParty.getStartTime()));

			TextView partyDistinctView = (TextView) headerView.findViewById(R.id.party_distinct);
			partyDistinctView.setText("北京市-海淀区");

			TextView partyAddressView = (TextView) headerView.findViewById(R.id.party_address);
			partyAddressView.setText(mParty.getAddress());
			headerView.findViewById(R.id.loc_me2party)
			.setOnClickListener(new View.OnClickListener(){
				@Override
				public void onClick(View v) {
					//LocationUtil.showUser2PartyRouterForGoogle(getSherlockActivity(), mParty);
					LocationUtil.showUser2PartyRouter(getSherlockActivity(), mParty);
				}		
			});
			TextView partyTitleView = (TextView) headerView.findViewById(R.id.text_i_want);
			partyTitleView.setText(mParty.getTitle());

			TextView partyDescView = (TextView) headerView.findViewById(R.id.text_party_desc);
			if (StringUtils.isBlank(mParty.getDescription())) {
				partyDescView.setText("这家伙很懒，什么也没有留下");
			} else {
				partyDescView.setText(mParty.getDescription());
			}
		}

		View mainView = inflater.inflate(R.layout.party_detail, container, false);
		mListView = (ListView) mainView.findViewById(R.id.post_list);

		mListView.addHeaderView(headerView);
		if (null == mPosts) {
			loadPartyPost(getActivity(), mParty.getPartyid(), 0, 0, page_size);
		}else{
			if (null != mPostListAdapter) {
				mListView.setAdapter(mPostListAdapter);
				mPostListAdapter.notifyDataSetChanged();
			}
		}

		View submitPostView = mainView.findViewById(R.id.btn_pub_post);
		submitPostView.setOnClickListener(this);

		mPostText = (EditText) mainView.findViewById(R.id.edit_text_pub_post);

		mPostTypeSelectButton = (ImageButton) mainView.findViewById(R.id.btn_post_type_select);
		mPostTypeSelectButton.setOnClickListener(this);

		mPostTypeSelectPanel = mainView.findViewById(R.id.post_type_select_panel);
		ImageButton postAddressButton = (ImageButton) mainView.findViewById(R.id.btn_post_address);
		postAddressButton.setOnClickListener(this);
		((ImageButton)mainView.findViewById(R.id.post_emotion_select)).setOnClickListener(this);
		((ImageButton)mainView.findViewById(R.id.post_image_select)).setOnClickListener(this);
		((ImageButton)mainView.findViewById(R.id.post_photo_select)).setOnClickListener(this);
		return mainView;
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		super.onCreateOptionsMenu(menu, inflater);
		getSherlockActivity().getSupportActionBar().setTitle(getString(R.string.title_party_detail));
		getSherlockActivity().getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		getSherlockActivity().getSupportActionBar().setHomeButtonEnabled(true);
	}

	@Override
	public boolean onOptionsItemSelected(com.actionbarsherlock.view.MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			getSherlockActivity().getSupportFragmentManager().popBackStack();
			return true;

		default:
			return super.onOptionsItemSelected(item);
		}
	}

	private void loadPartyPost(FragmentActivity activity, String partyid, int op, int start, int size) {
		new ListPostTask().execute(partyid, "0", Integer.toString(start), Integer.toString(size));
	}

	private class ListPostTask extends AsyncTask<String, Void, Boolean> {

		@SuppressWarnings("unused")
		int op, start, size;

		String partyid, error;

		@Override
		protected Boolean doInBackground(String... params) {
			if (mPosts == null || mPosts.size() == 0) {
				partyid = params[0];
				op = Integer.parseInt(params[1]);
				start = Integer.parseInt(params[2]);
				size = Integer.parseInt(params[3]);
				String url = ApiHelper.API_GET_PARTY_POSTS + "/" + partyid + "/" + start + "/" + size;
				String jsonValue = HttpUtil.GET(url);
				if (null == jsonValue) {
					error = getString(R.string.error_connection);
					return false;
				}
				JSONObject json = null;
				try {
					json = new JSONObject(jsonValue);
					if (1 == json.getInt("success")) {
						JSONArray list = json.getJSONArray("list");
						if (null == list) {
							error = getString(R.string.error_no_result);
							return false;
						}
						mPosts = new ArrayList<Post>();
						for (int i = 0; i < list.length(); i++) {
							Post post = Post.fromJSON(list.getJSONObject(i));
							mPosts.add(post);
						}
					}
				} catch (JSONException e) {
					Log.w(TAG, e);
					error = getString(R.string.error_json_format_error);
					return false;
				}
				return true;
			}
			return true;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			// mEmptyView.setVisibility(View.GONE);
			if (!result) {
				Toast.makeText(getActivity(), error, Toast.LENGTH_LONG).show();
			} else {
				if (null == mPostListAdapter) {
					mPostListAdapter = new PostListAdapter(getActivity());
					mListView.setAdapter(mPostListAdapter);
				}
				mPostListAdapter.notifyDataSetChanged();
			}
		}
	}

	private class PostTask extends AsyncTask<String, Void, Boolean> {

		int postType;

		@SuppressWarnings("unused")
		String error, partyid, userid, text, address, lonlat;

		Toast loadingToast;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(
					Context.INPUT_METHOD_SERVICE);
			if (inputMethodManager != null && mPostText != null)
				inputMethodManager.hideSoftInputFromWindow(mPostText.getWindowToken(), 0);
			loadingToast = Toast.makeText(getActivity(), "正在发布中...", Toast.LENGTH_LONG);
			loadingToast.show();
		}

		@Override
		protected Boolean doInBackground(String... params) {
			postType = Integer.parseInt(params[0]);
			partyid = params[1];
			userid = params[2];
			Map<String, String> postParams = new HashMap<String, String>();
			switch (postType) {
			case Post.PostContentType.Text:
				text = params[3];
				postParams.put("contenttype", params[0]);
				postParams.put("partyid", partyid);
				postParams.put("userid", userid);
				postParams.put("text", text);
				break;
			case Post.PostContentType.Address:
				lonlat = params[3];
				address = BaiduMapService.getAddressByLocation(lonlat);
				if (StringUtils.isBlank(address)) {
					error = "查询地理位置模块时出现问题";
					return false;
				}
				postParams.put("contenttype", params[0]);
				postParams.put("partyid", partyid);
				postParams.put("userid", userid);
				postParams.put("address", address);
				postParams.put("lonlat", lonlat);
				break;
			case Post.PostContentType.Image:
				text = params[3];
				postParams.put("contenttype", params[0]);
				postParams.put("partyid", partyid);
				postParams.put("userid", userid);
				//缩略图写待加
				postParams.put("imageurl", Constants.PIC_UPLOAD_URL+text);
				break;	
			default:
				break;
			}

			String jsonValue = HttpUtil.POST(ApiHelper.API_PUB_PARTY_POST, postParams);
			if (null == jsonValue) {
				error = getString(R.string.error_connection);
				return false;
			}
			JSONObject json = null;
			try {
				json = new JSONObject(jsonValue);
				if (1 == json.getInt("success")) {
					return true;
				}
			} catch (JSONException e) {
				Log.w(TAG, e);
				error = e.getMessage();
				return false;
			}
			return false;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			mPostTypeSelectPanel.setVisibility(View.GONE);
			if (null != loadingToast) {
				loadingToast.cancel();
			}
			if (result) {
				Post post = new Post();
				post.setContentType(postType);
				post.setPartyid(partyid);
				post.setUserid(userid);
				post.setPtime(new Date());
				switch (postType) {
				case Post.PostContentType.Text:
					post.setTextContent(text);
					break;
				case Post.PostContentType.Address:
					post.setAddressContent(address, lonlat);
					break;
				case Post.PostContentType.Image:
					//放置缩略图
					post.setImageContent(Constants.PIC_UPLOAD_URL+text+"!"+Constants.PIC_SMALL);
				break;	
				default:
					break;
				}
				mPosts.add(0, post);
				mPostListAdapter.notifyDataSetChanged();
				Toast.makeText(getActivity(), "发布成功", Toast.LENGTH_SHORT).show();
			}
		}
	}

	private class PostListAdapter extends BaseAdapter {

		@SuppressWarnings("unused")
		private Context mContext;

		private LayoutInflater mInflater;

		private final ImageDownloader imageDownloader = new ImageDownloader();

		public PostListAdapter(Context context) {
			super();
			this.mContext = context;
			this.mInflater = LayoutInflater.from(context);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			final Post post = mPosts.get(position);
			Log.d(TAG, "List的item开始getView");
			View view = mInflater.inflate(R.layout.post_item_of_text, mListView, false);
			TextView usernameTextView = (TextView) view.findViewById(R.id.text_post_author_name);
			RelativeLayout contentView = (RelativeLayout) view.findViewById(R.id.post_content_container);
			usernameTextView.setText(post.getUserid());
			switch (post.getContentType()) {
			case Post.PostContentType.Text:
				TextView postText = new TextView(getActivity());
				postText.setText(post.getText());
				contentView.addView(postText);
				break;
			case Post.PostContentType.Image:
				ImageView imageContentView = new ImageView(getActivity());
				imageContentView.setAdjustViewBounds(true);
				RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
						RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
				imageContentView.setLayoutParams(lp);
				imageContentView.setMaxHeight(200);
				imageContentView.setMaxWidth(200);
				imageContentView.setScaleType(ScaleType.CENTER_INSIDE);
				contentView.addView(imageContentView);
				final FragmentActivity fa = getSherlockActivity();
				imageContentView.setOnClickListener(new View.OnClickListener() {			
					@Override
					public void onClick(View v) {
						ShowPictureFragment sp = new ShowPictureFragment()
								.setUrl(post.getImageUrl()).setPreFragment((Fragment)sf).setPreTagStr(Constants.FRAGMENT_PARTY_DETAIL);
						FragmentTransaction ft = fa.getSupportFragmentManager().beginTransaction();
						ft.replace(R.id.main_fragment_container, sp, Constants.FRAGMENT_TAG_PICTRUE_DETAIL);
						ft.addToBackStack(null);
						ft.commit();
					}
				});
				imageDownloader.download(post.getImageUrl(), imageContentView);
				break;
			case Post.PostContentType.Address:
				TextView addressContentView = new TextView(getActivity());
				addressContentView.setText(post.getAddress());
				addressContentView.setBackgroundResource(R.drawable.location_msg);
				addressContentView.setTextColor(getResources().getColor(R.color.text_color_write));
				contentView.addView(addressContentView);
				addressContentView.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						LocationUtil.showUser2UserRouter(getActivity(),post);
					}
				});
				break;
			default:
				break;
			}
			return view;
		}

		@Override
		public int getCount() {
			return mPosts.size();
		}

		@Override
		public Object getItem(int position) {
			return mPosts.get(position);
		}

		@Override
		public long getItemId(int position) {
			return mPosts.get(position).hashCode();
		}

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_pub_post:
			if (null != mPostText) {
				String postText = mPostText.getText().toString();
				if (StringUtils.isNotBlank(postText)) {
					UserSession session = UserSessionManager.getUserSession(getActivity());
					if (null != session) {
						submitTextPost(mParty.getPartyid(), session.getUserid(), postText);
					}
				}
			}
			break;
		case R.id.btn_post_type_select:
			if (null != mPostTypeSelectPanel) {
				mPostTypeSelectPanel.setVisibility(View.GONE == mPostTypeSelectPanel.getVisibility() ? View.VISIBLE
						: View.GONE);

			}
			break;
		case R.id.post_emotion_select:
			
			break;
		case R.id.post_image_select:
			Log.v(TAG, "调用相册");
    		picHandler.startActivityAlbum(getSherlockActivity(),PictureHandler.REQUEST_PARTYDETAIL_ALBUM);
			break;
		case R.id.post_photo_select:
			Log.v(TAG, "调用相机");
			//调用
	      	picHandler.startActivityCamera(getSherlockActivity(),PictureHandler.REQUEST_PARTYDETAIL_CAMERA);
			break;
		case R.id.btn_post_address:
			UserSession session = UserSessionManager.getUserSession(getActivity());
			String latlng = session.getLatlng();
			if (StringUtils.isNotBlank(latlng)) {
				submitAddressPost(mParty.getPartyid(), session.getUserid(), latlng);
			}
		default:
			break;
		}
	}

	private void submitAddressPost(String partyid, String userid, String lonlat) {
		PostTask postTask = new PostTask();
		postTask.execute("2", partyid, userid, lonlat);
	}

	private void submitTextPost(String partyid, String userid, String postText) {
		PostTask postTask = new PostTask();
		postTask.execute("0", partyid, userid, postText);
	}
}
